package com.sui.bigdata.rtcadmin.util;

import com.alibaba.fastjson.JSONObject;
import com.feidee.fdcommon.model.StringResponse;
import com.feidee.fdcommon.util.HttpUtil;
import com.google.common.collect.Maps;
import com.sui.bigdata.rtcadmin.constant.AppConstant;
import com.sui.bigdata.rtcadmin.constant.JobConstant;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author YongChen
 * @date 2019/12/11 12:15
 * @description
 * @email yong_chen@sui.com
 */
public class SendMsgUtils {
    protected static final Logger logger = LoggerFactory.getLogger(SendMsgUtils.class);

    public static void sendJobRestartFailMsg(String url, String jobName, String developer, String appStatus, String trackUrl, int todayRestartTimes){
        String alarmInfo = String.format("Flink实时标签-任务监控  %s  任务状态为：%s，在 %s 重启失败！今日重启次数：%s，请 %s 点击：%s 了解更多细节!",
                jobName,appStatus,getCurrentTime(), todayRestartTimes,developer,trackUrl);
        if("test".equals(AppConstant.ENV)){
            sendMsg(url,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(url,"【线上任务】 " + alarmInfo);
        }
    }

    public static void sendJobRestartSuccessMsg(String url, String jobname ,String status,String applicationId, int todayRestartTimes) {
        String alarmInfo = String.format("Flink实时标签-任务监控  %s 任务状态为：%s，在 %s 重启成功！今日重启次数：%s，重启前的applicationId为：%s",
                jobname,status,getCurrentTime(), todayRestartTimes,applicationId);
        if("test".equals(AppConstant.ENV)){
            sendMsg(url,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(url,"【线上任务】 " + alarmInfo);
        }
    }

    public static void sendBackpressureMsg(String alarmUrl, String jobName, String developer, String level, String ratio, String description, String webUrl){
        String alarmInfo = String.format("Flink实时标签-反压监控 the subtask of %s called %s , Backpressure  level: %s ratio: %s at %s.please %s click %s for more details!",
                jobName, description, level, ratio, getCurrentTime(), developer, webUrl);
        if("test".equals(AppConstant.ENV)){
            sendMsg(alarmUrl,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(alarmUrl,"【线上任务】 " + alarmInfo);
        }
    }

    public static void sendBackpressureMsg(String alarmUrl, String jobName, String level, String ratio, String description) {
        String alarmInfo = String.format("Flink实时标签-反压监控 the subtask of %s called %s , Backpressure recover, current  level: %s ratio: %s at %s.",
                jobName, description, level, ratio, getCurrentTime());
        if("test".equals(AppConstant.ENV)){
            sendMsg(alarmUrl,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(alarmUrl,"【线上任务】 " + alarmInfo);
        }
    }

    public static void sendMemoryUsedMsg(String alarmUrl, String jobName, String developer, String memoryPercent,String taskManager ,  String webUrl) {
        String alarmInfo = String.format("Flink实时标签-内存监控 the taskManager of %s called %s , memory used %s at %s.please %s click %s for more details!",
                jobName,taskManager,memoryPercent,getCurrentTime(), developer, webUrl);
        if("test".equals(AppConstant.ENV)){
            sendMsg(alarmUrl,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(alarmUrl,"【线上任务】 " + alarmInfo);
        }
    }

    public static void sendMemoryUsedMsg(String alarmUrl, String jobName, String memoryPercent,String taskManager) {
        String alarmInfo = String.format("Flink实时标签-内存监控 the taskManager of %s called %s , memory used  recover ,current %s at %s.",
                jobName,taskManager,memoryPercent,getCurrentTime());
        if("test".equals(AppConstant.ENV)){
            sendMsg(alarmUrl,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(alarmUrl,"【线上任务】 " + alarmInfo);
        }
    }

    public static void sendSparkAppRestartFailMsg(String url, String jobName, String developer, String appStatus, String trackUrl){
        String alarmInfo = String.format("Spark-任务监控  %s  change to %s  after restart three times at %s.Please %s click %s for more details!",
                jobName,appStatus,appStatus,developer,trackUrl);
        if("test".equals(AppConstant.ENV)){
            sendMsg(url,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(url,"【线上任务】 " + alarmInfo);
        }
    }

    public static void sendSparkAppRestartSuccessMsg(String url, String jobname ,String status,String applicationId) {
        String alarmInfo = String.format("Spark-任务监控  %s auto %s change restart  success  at %s.Before the applicationId is %s！",jobname,status,getCurrentTime(),applicationId);
        if("test".equals(AppConstant.ENV)){
            sendMsg(url,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(url,"【线上任务】 " + alarmInfo);
        }
    }

    public static void sendYarnDisconnectMsg(String url) {
        String alarmInfo = String.format("计算平台:无法连接到yarn at %s.",getCurrentTime());
        if("test".equals(AppConstant.ENV)){
            sendMsg(url,"【测试任务】 " + alarmInfo);
        }else{
            sendMsg(url,"【线上任务】 " + alarmInfo);
        }
    }


    public static void sendMsg(String url, String alarmInfo) {
        Map<String, String> body = Maps.newHashMap();
        body.put("text", alarmInfo);
        StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(body), "UTF-8");
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(stringEntity);

        StringResponse response = null;
        try {
            response = HttpUtil.post(httpPost);
            if ("success".equals(response.getResponseBody())) {
                logger.info(" send msg succeed. url：{} ,alarmInfo: {}.",url,alarmInfo);
            }else {
                logger.info(" send msg fail. url：{} ,alarmInfo: {}.",url,alarmInfo);
            }
        } catch (Exception e) {
            logger.info(" send msg fail. url：{} ,alarmInfo: {}.",url,alarmInfo);
        }
    }
    public static String getCurrentTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return  df.format(new Date(System.currentTimeMillis()));
    }
}
